﻿
var list_id;
var colModelLocal;
var dimtable_name;
var filepath;
var rule_id;
var imp_id;
var xref_arr;
var importProcData; //import process grid data
var listIdImport;
var filename;
var isPopulatedRel = false;
var Childlist_id;

function BindMstCombo(opr, id, comboid) {
    ////////debugger;
    $.ajax({
        async: true,
        type: 'POST',
        url: "MasterCallback.aspx?operation=" + opr + "&id=" + id,
        success: function (str) {
            ////////debugger
            var data = eval('(' + str + ')');
            $("#" + comboid).empty();
            $("#tmplOptions").tmpl(data).appendTo("#" + comboid);
        }
    });
}

//original without url parameter
//function loadGriddata() {

//    $.ajax({
//        async: true,
//        type: 'GET',
//        url: "MasterCallback.aspx?operation=get_griddata&dimtable_name=" + dimtable_name + "&list_id=" + list_id,
//        data: "",
//        dataType: "json",
//        success: function (result) {
//            ////////debugger
//            var colD = result.datarow, colN = result.columns, colM = result.colModelList;
//            $("#dataGrid").GridUnload(); // destroy the grid saving the table and pager

//            jQuery("#dataGrid").jqGrid({
//                data: colD,
//                datatype: 'local',
//                gridview: true,
//                colNames: colN,
//                colModel: colM,
//                caption: "Master Data",
//                editurl: "MasterCallback.aspx?dimtable_name=" + dimtable_name + "&list_id=" + list_id,
//                rowNum: 10,
//                pager: '#pager',
//                sortname: result.primarykey,
//                sortorder: "desc",
//                //width: "100%",
//                width: "800px",
//                height: "100%",
//                scrollOffset: 18,
//                closeAfterEdit: true,
//                ignoreCase: true,
//                loadComplete: function (data) {
//                    // //////debugger
//                    jQuery("#dataGrid").hideCol(result.primarykey);
//                    jQuery("#dataGrid").setGridWidth(980, true);
//                },
//                loadError: function (xhr, status, error) {
//                    ////////debugger
//                    alert('error');
//                }
//            });
//            ////////debugger
//            navGridd();
//            //jQuery("#dataGrid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: true });

//        },
//        error: function (x, e) {
//            //////debugger
//            alert(x.readyState + " " + x.status + " " + e.msg);
//        }
//    });
//}

function loadGriddata() {

    $.ajax({

        async: true,
        type: 'GET',
        url: "MasterCallback.aspx?operation=get_gridColdata&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&blink=false",
        data: "",
        dataType: "json",
        success: function (result) {
            // //////debugger
            var colN = result.columns, colM = result.colModelList;
            $("#dataGrid").GridUnload(); // destroy the grid saving the table and pager

            jQuery("#dataGrid").jqGrid({
                url: "MasterCallback.aspx?operation=get_griddata&dimtable_name=" + dimtable_name + "&list_id=" + list_id,
                datatype: 'json',
                gridview: true,
                colNames: colN,
                colModel: colM,
                caption: "Master Data",
                editurl: "MasterCallback.aspx?dimtable_name=" + dimtable_name + "&list_id=" + list_id,
                rowNum: 10,
                pager: '#pager',
                sortname: result.primarykey,
                sortorder: "desc",
                //width: "100%",
                width: "800px",
                height: "100%",
                scrollOffset: 18,
                closeAfterEdit: true,
                ignoreCase: true,
                prmNames: { id: "_id" },
                multiselect: true,
                loadComplete: function (data) {
                    //debugger;
                    jQuery("#dataGrid").hideCol(result.primarykey);
                    jQuery("#dataGrid").setGridWidth(920, true);
                    //jQuery("#dataGrid").setGridWidth("900", true);

                    //show show button                  
                    if ($("#dataGrid").getGridParam("reccount") > 0) {
                        $("#MSubmit_Show").show();
                        $("#MSubmit_Rel").show();
                    }
                    else {
                        $("#MSubmit_Show").hide();
                        $("#MSubmit_Rel").hide();
                    }
                },
                loadError: function (xhr, status, error) {
                    //debugger;
                    alert('error');
                }
            });

            // //////debugger
            navGridd();
            // $("#dataGrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false }); 
            //jQuery("#dataGrid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: true });

        },
        error: function (x, e) {
            //////debugger
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
}


function afterSub(response, postdata) {
    // //////debugger
    if (response.responseText == "true") {
        alert("saved successfully");
        return [true, "saved successfully !"]
    }
    else if (response.responseText == "false") {
        //alert("some error in save !");
        return [false, "some error in save !"]
    }
}

function navGridd() {
    //debugger;
    // alert("ll");
    jQuery("#dataGrid").jqGrid('navGrid', '#pager', { del: true, edit: true, add: true, search: true },
    {//edit
    afterSubmit: afterSub,
    closeAfterEdit: true,
    reloadAfterSubmit: false,
    width: "500",
    onInitializeForm: function (formid) {
        // debugger;
        //for  * sign for mandatory field  and datepicker
        colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
        var appendtag = "<font style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";

        for (i = 0, len = colModelLocal.length; i < len; i++) {
            var edtrul = colModelLocal[i].editrules;
            var name = colModelLocal[i].name;
            if (edtrul != undefined) {
                if (edtrul.date === true) {
                    $("#" + name, formid).datepicker();
                }
                if (edtrul.required === true) {
                    var relTo = $("#" + name, formid);
                    $(appendtag).insertAfter(relTo);
                }
            }
        }

    }
},
{//new
    // afterSubmit: afterSub,
    afterSubmit: function (response) {
        if (response.responseText == "false") {
            return [false, "some error in save !"]
        }
        else {
            return [true, "saved successfully !", response.responseText]
        }
    },
    closeAfterAdd: true,
    reloadAfterSubmit: false,
    width: "500",
    onInitializeForm: function (formid) {
        // debugger;
        //for  * sign for mandatory field  and datepicker
        colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
        var appendtag = "<font style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";

        for (i = 0, len = colModelLocal.length; i < len; i++) {
            var edtrul = colModelLocal[i].editrules;
            var name = colModelLocal[i].name;
            if (edtrul != undefined) {
                if (edtrul.date === true) {
                    $("#" + name, formid).datepicker();
                }
                if (edtrul.required === true) {
                    var relTo = $("#" + name, formid);
                    $(appendtag).insertAfter(relTo);
                }
            }
        }
    }
},
{//delete
    afterSubmit: function (response) {
        ////////debugger
        if (response.responseText == "true") {
            return [true, "deleted successfully !"]
        }
        else if (response.responseText == "false") {
            return [false, "some error in delete !"]
        }
        else {
            return [false, response.responseText]
        }
    },
    closeAfterEdit: true,
    reloadAfterSubmit: false
},
{//complex search
    multipleSearch: true,
    multipleGroup: false,
    showQuery: true,
    postSqlQuery: true
    //, showRel: true,
    // odata: ['equal', 'not equal', 'less', 'less or equal', 'greater', 'greater or equal', 'begins with', 'does not begin with', 'is in', 'is not in', 'ends with', 'does not end with', 'contains', 'does not contain']
}
);
}


//fill dimension + xref+ gray data
function loadDimData() {

    //debugger;
    //var mast_id = jQuery("#dataGrid").jqGrid('getGridParam', 'selrow');
    var mast_id = jQuery("#dataGrid").getGridParam('selarrrow');

    if (mast_id.length > 1) {

        $("#editSrcError").show();
        $("#editSrcError").fadeOut(8000);
        //alert("Please Select single dimension for Edit Source ! ");
        return false;
    }
    else {

        //clear graph tab data
        ClearGraphTab();

        dimtable_name = $("#drp_mst option:selected").data("TableName");
        list_id = $("#drp_mst").val();

        if (mast_id == null || mast_id == "undefined") {
            alert("Please Select dimension to show source and grey data");
            $("#MSubmit_Apply").css('display', 'none');
            //$("#MSubmit_Apply").hide();
            return false;
        }
        else {

            $.ajax({
                async: true,
                type: 'POST',
                url: "MasterCallback.aspx?operation=select_dim&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&mast_id=" + mast_id,
                success: function (str) {
                    //debugger;

                    var data = eval('(' + str + ')');
                    $("#M_DimMast").empty();

                    $("#tmpldim").tmpl(data).appendTo("#M_DimMast");

                    // $("#M_DimMast").css("display", "block");
                    $("#M_DimMast").show();
                    $("#divRel").hide();
                    //to make dimension master table re-sizable
                    ////////debugger
                    //remove the previous tags of div for drag
                    $('div[id^="M_DimMast_id"]').remove();
                    $("#M_DimMast").simpleResizableTable();

                    $("#MSubmit_Apply").css('display', 'block');
                    //$("#MSubmit_Apply").show();
                }
            });
        }
    }

}

//applt button click
function apply_click(rowindex) {

    var th_xrf = "thxref_" + rowindex;
    //hid_xref  //.attr('bgcolor', 'aqua');

    var arr = $('td[id^="xref_' + rowindex + '"][bgcolor="aqua"]')[0].attributes["id"].value.split('_');
    //$('td[id^="xref_' + rowindex + '"][bgcolor="aqua"]')[0].attributes["id"]
    var xrefcol_index = arr[2];

    //th_control value
    var thCtrl_val = $("#thxref_" + xrefcol_index)[0].attributes["value"].value;

    //change the applied td bgcolor
    $('td[id^="xref_' + rowindex + '"][bgcolor="silver"]').attr('bgcolor', 'white');
    $('td[id^="xref_' + rowindex + '"][bgcolor="aqua"]').attr('bgcolor', 'silver');


    //hide the button
    $('#btn_' + rowindex)[0].style.display = "none";
    //show the clear button
    $('#btnC_' + rowindex)[0].style.display = "block";

    //set new value
    $("#hidxref_" + rowindex).attr('value', thCtrl_val);
    $("#hidxref_" + rowindex).attr('changed', 'true');
    //debugger;        
    //set text of applied source
    $('#input_m' + rowindex).val(jQuery.trim($('td[id="xref_' + rowindex + "_" + +arr[2] + '"]', "#M_DimMast").html()));

}


//clear button click
function clear_click(rowindex) {
    ////////debugger

    var th_xrf = "thxref_" + rowindex;
    //hid_xref  //.attr('bgcolor', 'aqua');

    var arr = $('td[id^="xref_' + rowindex + '"][bgcolor="#FFFFC6"]')[0].attributes["id"].value.split('_');
    //$('td[id^="xref_' + rowindex + '"][bgcolor="aqua"]')[0].attributes["id"]
    var xrefcol_index = arr[2];

    //th_control value
    var thCtrl_val = $("#thxref_" + xrefcol_index)[0].attributes["value"].value;

    //change the applied td bgcolor
    $('td[id^="xref_' + rowindex + '"][bgcolor="silver"]').attr('bgcolor', 'white');
    $('td[id^="xref_' + rowindex + '"][bgcolor="aqua"]').attr('bgcolor', 'white');

    //hide the apply button
    //$('#btn_' + rowindex)[0].style.display = "none";

    //hide the clear button
    $('#btnC_' + rowindex)[0].style.display = "none";
    $('#btn_' + rowindex)[0].style.display = "none";

    //set new value
    $("#hidxref_" + rowindex).attr('value', thCtrl_val);
    $("#hidxref_" + rowindex).attr('changed', 'false');

    //debugger;
    //set text of applied source
    $('#input_m' + rowindex).val(jQuery.trim($("'#hidxref_" + rowindex + "'", "#M_DimMast").attr("data")));

}


function tableMaster_dblClick(event, object) {
    // debugger;

    if (event.target.attributes["id"].value.substr(0, 1)) {

        if ($('#' + event.target.attributes["id"].value)[0].attributes['bgcolor'].value != "#FFFFC6") {
            var td_id = event.target.attributes["id"];
            //get the tr index 
            // var index = event.target.attributes["id"].value.substr(5, 1);
            var arr = event.target.attributes["id"].value.split('_');
            var index = arr[1];

            //control td of master
            var ctrl_td = "m" + index;
            //if already any selected td is there in that row- de-select that
            $('td[id^="xref_' + index + '"][bgcolor="aqua"]').attr('bgcolor', 'white');
            //$('td[id^="xref_' + index + '"][bgcolor="silver"]').attr('bgcolor', 'white');
            //clear_click(index);

            //highlight dbl-clicked td

            $('#' + event.target.attributes["id"].value).attr('bgcolor', 'aqua');
            $('#btn_' + index)[0].style.display = "block";

            //$(".dimText",) // $('input[ ],"")             $("td.dimText:text",)   //$("input.dimText:text",) 

            //col index
            var colindex = arr[2];
            xref_th = "thxref_" + colindex;
            //$('#' +xref_th)[0].attributes["value"].value;
        }
    }
}


//save dimension data
function saveMasterData() {

    // debugger;

    if ($('td[id^="xref_"][bgcolor="silver"]').length != 0) {

        dimtable_name = $("#drp_mst option:selected").data("TableName");
        list_id = $("#drp_mst").val();
        var mast_id = jQuery("#dataGrid").jqGrid('getGridParam', 'selrow');

        var jsonstring = "["

        $('input[type="hidden"][id^="hidxref_"]').each(function (i) {
            ////////debugger
            var colName = $(this)[0].attributes["colname"].value;
            var xref_id = $(this)[0].attributes["value"].value;
            var bchanged = $(this)[0].attributes["changed"].value;
            //alert(colname + "--" + xref_id);

            // jsonstring = jsonstring + '{"colname" :  "' + colName + '", "colvalue" :  "' + xref_id + '"},';
            jsonstring = jsonstring + '{"colname" :  "' + colName + '", "colvalue" :  "' + xref_id + '", "changed" :  "' + bchanged + '"},';

        });

        ////////debugger
        jsonstring = jsonstring.substring(0, jsonstring.length - 1) + "]";

        $.ajax({
            async: true,
            type: 'POST',
            url: "MasterCallback.aspx?operation=change_source&chgVal=" + jsonstring + "&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&mast_id=" + mast_id,
            success: function (str) {
                ////////debugger
                if (str == "false") {
                    alert("Error in save !");
                    return false;
                }
                else {
                    //$("#hdn_bAttrVal").attr('value', "1"); 
                    alert("saved successfully !");
                    loadDimData();
                    return false;
                }
            }
        });
    }
    else {

        alert("There is no change in source to save!");
        return false;
    }
}


//////////////////////////////////////////////////////////////////////////
//                   Imoport tab code starts from here 
//////////////////////////////////////////////////////////////////////////



//import data section for excel
function ImportData() {

    //debugger;
    dimtable_name = $("#drp_mstM option:selected").data("TableName");
    list_id = $("#drp_mstM").val();
    filepath = $("#frameFile").contents().find('#fileupload1')[0].value;
    filename = $("#txtUpload").val();  //txtUpload
    var sheetname = $("#txtExcel").val();  //txtExcel

    if (sheetname == null || sheetname == "undefined" || sheetname == "") {
        alert("Please Put Excel Sheet Name to Import Data !");
        return false;
    }
    else {

        if (filename == null || filename == "undefined" || filename == "") {
            alert("Please Submit Excel file to Import Data !");
            return false;
        }
        else {

            //debugger
            if (list_id == null || list_id == "undefined" || list_id == "") {
                alert("Please Select dimension to Import Data !");
                return false;
            }
            else {
                $.ajax({
                    async: true,
                    type: 'POST',
                    url: "MasterCallback.aspx?operation=ImportData&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&filename=" + filename + "&sheetname=" + sheetname, //sheetname
                    success: function (str) {
                        //debugger;
                        if (str == "false") {
                            alert("Error in Import !");
                            return false;
                        }
                        else if (str == "notmapped") {
                            alert("Columns are not mapped ! Can't be Imported !");
                            return false;
                        }
                        else if (str == "noSheet") {
                            alert("Sheet Name Doesn't exists ! Can't be Imported !");
                            return false;
                        }
                        else {
                            ////debugger
                            //$("#hdn_bAttrVal").attr('value', "1");   
                            var arr = str.split('~');
                            $("#hid_ImpId").val(arr[1]);
                            showImportData(arr[0], arr[1], filename);
                            //if ($("#dtImport").getGridParam("reccount") > 0) {
                            //show match-rule button                       
                            $("#MSubmit_matchRule").show();
                            $("#MSubmit_matchRule").removeAttr('disabled');
                            //}
                            ////debugger
                            //clear import file name
                            $("#txtUpload").val('');  //txtUpload 
                            $("#txtExcel").val('');
                            return false;
                        }
                    }
                });
            }
        }
    }
}

// match rule
function matchRule() {

    //debugger;
    var selection = $('input:radio[name=radiogrp_imp]:checked').val();

    if ($("#dtImport").getGridParam("reccount") > 0) {

        if ($("#drp_mstM option:selected").data("TableName") != null && $("#drp_mstM option:selected").data("TableName") != "" && $("#drp_mstM option:selected").data("TableName") != undefined) {
            dimtable_name = $("#drp_mstM option:selected").data("TableName");
        }
        if ($("#drp_mstM").val() != null && $("#drp_mstM").val() != "" && $("#drp_mstM").val() != undefined) {
            list_id = $("#drp_mstM").val();
        }
        imp_id = $("#hid_ImpId").val();

        if (list_id == null || list_id == "undefined") {
            alert("Please Select dimension to Execute rule !");
            return false;
        }
        else {
            $.ajax({
                async: true,
                type: 'POST',
                url: "MasterCallback.aspx?operation=matchRule&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&imp_id=" + imp_id,
                success: function (result) {
                    //debugger

                    if (result == "false") {
                        alert("Error in match rule !");
                        return false;
                    }
                    else {
                        //debugger
                        var bflag;
                        if ($('#tabsDimm').tabs('length') < 4) {
                            bflag = true;
                        }
                        else {
                            bflag = false;
                        }

                        fillMatchGrid(result, imp_id, bflag);
                        //hide execute rule button
                        $("#MSubmit_matchRule").hide();
                        //debugger;
                        //if from existing imported data 
                        // if imp_id is there update is_executed
                        //imp_arr = jQuery("#dtgridExist").jqGrid('getCol', 'IMP_ID', false, '');     
                        if (jQuery("#dtgridExist").jqGrid('getCell', imp_id, 'IMP_ID') != false) {
                            jQuery("#dtgridExist").jqGrid('setCell', imp_id, 'IS_EXECUTED', 'Yes');
                        }

                    }
                }
            });
        }
    }
    else {

        alert("There is no row to execute rule !");
        return false;
    }
    //}
}

function fillMatchGrid(result, imp_id, bnewtab) {
    //debugger

    //$("#dtMatch").GridUnload(); // destroy the grid saving the table and pager
    var rule_id = "1";
    //add match tab
    addMatchTab(result, imp_id, bnewtab);

    //add manual tab
    addManualTab(result, imp_id, bnewtab);

    var arr = result.split('^');
    //add unmatch tab
    addUnMatchTab(arr[0], imp_id, bnewtab);

    //fill rule combo
    var data = eval('(' + arr[1] + ')');

    $("#drp_Matchrule,#drp_Manualrule").empty();
    $("#tmplOptions").tmpl(data).appendTo("#drp_Matchrule,#drp_Manualrule");

    //debugger;
    $("#tabsDimmCaption").text(filename);

}

//add manual tab dynamically
function addManualTab(str, imp_id, bAddtab) {

    //////debugger

    var arr = str.split('^');
    var result = arr[0];
    var tabname = "Manual";

    //if addtab=true then do this
    if (bAddtab == true) {
        addtab(tabname, "Manual Match");
    }

    var result = eval('(' + arr[0] + ')');
    var colN = result.columns, colM = result.colModelList;

    var dtgrid = "#dtgrid" + tabname;
    $(dtgrid).GridUnload(); // destroy the grid saving the table and pager

    jQuery(dtgrid).jqGrid({
        async: false,
        url: "MasterCallback.aspx?operation=get_griddataManualRule&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=0" + "&imp_id=" + imp_id,
        datatype: 'json',
        gridview: true,
        colNames: result.columns,
        colModel: result.colModelList,
        caption: "Master Data",
        pager: '#pg' + tabname,
        //rowList: [10, 20, 30],
        sortorder: "desc",
        width: "800px",
        height: "100%",
        sortable: false,
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        pgbuttons: false,
        rowNum: -1,
        multiselect: true,
        loadComplete: function (data) {
            //////debugger
            //color golden records
            $(this).find("tr.jqgrow:has(td:[aria-describedby*='_MANUAL_RULE_ID'][title='0.00'])").addClass("golden");

            jQuery(dtgrid).hideCol(result.primarykey);
            jQuery(dtgrid).setGridWidth("850", true);

            //hide select all check box
            $("#cb_dtgridManual").hide();

            xref_arr = jQuery(dtgrid).jqGrid('getCol', 'XREF_ID', false, '');
            var bflag = false;

            if (data.rows.length > 0) {
                for (var i = 0; i < data.rows.length; i++) {

                    var rowid = data.rows[i].cell[0];
                    var val = $(this).jqGrid('getCell', rowid, 'MANUAL_RULE_ID');
                    var xref_id = $(dtgrid).getCell(rowid, 'XREF_ID');
                    //var dim_id = $(this).jqGrid('getCell', rowid, 'DIM_ID');
                    var dim_id = $(this).jqGrid('getCell', rowid, 'MASTER_ID');
                    $("#jqg_dtgrid" + tabname + "_" + rowid).attr('xrefid', xref_id);
                    //////debugger
                    if (val == '0.00') {
                        $("#jqg_dtgrid" + tabname + "_" + rowid).hide();
                        $("#jqg_dtgrid" + tabname + "_" + rowid).attr('disabled', 'true');

                        if (bflag == true) {
                            $("#" + rowid, dtgrid).find("input[type='checkbox'][offval='no']").attr('disabled', 'true');
                            $("#" + rowid, dtgrid).find("input[type='checkbox'][offval='no']").hide();
                        }

                        $("#" + rowid, dtgrid).find("input[type='checkbox'][offval='no']").attr('xrefid', xref_id);
                        $("#" + rowid, dtgrid).find("input[type='checkbox'][offval='no']").attr('dimid', dim_id);

                    }
                    else {

                        $("#" + rowid, dtgrid).find("input[type='checkbox'][offval='no']").attr('disabled', 'true');
                        $("#" + rowid, dtgrid).find("input[type='checkbox'][offval='no']").hide();

                        if ((i + 2) < data.rows.length) {
                            // take it from xref object
                            if (xref_arr[i + 1] == xref_arr[i + 2]) {
                                bflag = false;
                                $("#jqg_dtgrid" + tabname + "_" + rowid).attr('multimast', 'true');
                                $("#jqg_dtgrid" + tabname + "_" + rowid).attr('disabled', 'true');
                            }
                            else {
                                bflag = true;
                                $("#jqg_dtgrid" + tabname + "_" + rowid).attr('multimast', 'false');
                            }
                        }
                        else {
                            bflag = true;
                        }
                    }
                }

                //set width and check-box in center           
                $('input[type="checkbox"][offval="no"]', dtgrid).parent().css('text-align', 'center'); // text-align: center;
                $('input[type="checkbox"][offval="no"]', dtgrid).parent().css('width', '20px');
            }
        },
        beforeSelectRow: function (rowid, e) {
            //////debugger
            var cbsdis = $("tr#" + rowid + ".jqgrow > td > input.cbox:disabled", dtgrid);
            if (cbsdis.length === 0) {
                return true;    // allow select the row
            } else {
                return false;   // not allow select the row
            }
        },
        onSelectAll: function (aRowids, status) {
            if (status) {
                // uncheck "protected" rows
                var cbs = $("tr.jqgrow > td > input.cbox:disabled", dtgrid);
                cbs.removeAttr("checked");
                jQuery(dtgrid).find("tr.jqgrow:has(td > input.cbox:disabled)").removeClass("ui-state-highlight");

                //if multiple selection is true then don't select
                $("tr.jqgrow > td > input.cbox[multimast='true']", dtgrid).attr('checked', false);
                jQuery(dtgrid).find("tr.jqgrow:has(td > input.cbox[multimast='true'])").removeClass("ui-state-highlight");

                //////debugger
                $('input[type="checkbox"][offval="no"]:checked', dtgrid).each(function () {
                    //jsonstring = jsonstring + '{"Id" :  "' + $(this).text() + '"},';
                    //////debugger
                    var xrefid = $(this).attr("xrefid");

                    //$("#jqg_dtgridMatch_" + rowid, "#dtgridMatch").attr("checked", true);
                    $('input.cbox[type="checkbox"][xrefid="' + xrefid + '"]:visible', dtgrid).attr("checked", true);
                    jQuery(dtgrid).find("tr.jqgrow:has(td > input.cbox[type='checkbox'][xrefid='" + xrefid + "']:visible)").addClass("ui-state-highlight");

                });

                //modify the selarrrow parameter
                jQuery(dtgrid).p.selarrrow = jQuery(dtgrid).find("tr.jqgrow:has(td > input.cbox:checked)")
                                .map(function () { return this.id; }) // convert to set of ids
                                .get(); // convert to instance of Array
            }
            else {
                //////debugger
                $('input[type="checkbox"][offval="no"]', dtgrid).attr("checked", status);
            }
        },
        loadError: function (xhr, status, error) {
            alert('error');
        }
    });

    jQuery(dtgrid).jqGrid('navGrid', "#pg" + tabname, { edit: false, add: false, del: false, search: true });
    //jQuery(dtgrid).jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false }); 

}

function MasterChkClick(elm) {
    // debugger
    var dtgrid = "#dtgridManual";
    var tabname = "Manual";
    var xrefid = elm.target.attributes["xrefid"].value;
    var dimid = elm.target.attributes["dimid"].value;
    var index = jQuery.inArray(xrefid, xref_arr);
    var rowid = index + 1;

    if (elm.target.checked == true) {
        $('input[type="checkbox"][offval="no"][xrefid="' + xrefid + '"]', dtgrid).attr('checked', false);
        $('input[type="checkbox"][offval="no"][dimid="' + dimid + '"]', dtgrid).attr('checked', true);
        $("#jqg_dtgrid" + tabname + "_" + rowid, dtgrid).attr("checked", "checked");

        jQuery(dtgrid).find("tr" + "#" + rowid).addClass("ui-state-highlight");

    }
    else {
        $("#jqg_dtgrid" + tabname + "_" + rowid, dtgrid).attr("checked", false);
        jQuery(dtgrid).find("tr" + "#" + rowid).removeClass("ui-state-highlight");
    }
}

//add match tab dynamically
function addUnMatchTab(str, imp_id, bAddtab) {
    //debugger

    //if addtab=true then do this
    if (bAddtab == true) {
        addtab("UnMatch", "Un-Match Result");
    }

    var result = eval('(' + str + ')');
    var colN = result.columns, colM = result.colModelList;

    //jsons
    //debugger;

    $("#dtgridUnMatch").GridUnload(); // destroy the grid saving the table and pager

    var url = "MasterCallback.aspx?operation=get_griddataUnMatchRule&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&imp_id=" + imp_id;
    fillgridMatch(result, "#dtgridUnMatch", "#pgUnMatch", "800px", "350px", "Un-Match Data", "", url, true);
    jQuery("#dtgridUnMatch").jqGrid('navGrid', "#pgUnMatch", { edit: false, add: false, del: false, search: true });

}


//to fill jqgird - function with Add , Edit and Delete for dimension col 
function fillgridMatch(result, tblname, pgname, gWidth, gHeight, caption, editurll, url, bmultiselect) {

    var colN = result.columns, colM = result.colModelList;

    $.each(colM, function (index, el) {
        if (el.index == 'SOURCE_ID' && el.index == 'MASTER_ID' && el.index == 'MANUAL_RULE_ID') {
            colN.splice(index, 1);
            colM.splice(index, 1);
        }
    });

    if (tblname == "#dtgridUnMatch") {
        colN.splice(1, 1); // Remove 1 item starting from index 1 
        colM.splice(1, 1); // Remove 1 item starting from index 1 
    }

    jQuery(tblname).jqGrid({
        url: url,
        datatype: 'json',
        gridview: true,
        colNames: colN,
        colModel: colM,
        caption: caption,
        loadonce: true,
        pager: pgname,
        sortname: result.primarykey,
        sortorder: "asc",
        width: "800px",
        height: "100%",
        sortable: false,
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        gridview: true,
        viewrecords: true,
        pgbuttons: false,
        rowNum: -1,
        //        // define a model where all fields are not sortable,
        //        // this setting overwrite the deafult one for all fields
        //        cmTemplate: { sortable: false },
        multiselect: bmultiselect,
        loadComplete: function (data) {
            //////debugger
            jQuery(tblname).hideCol(result.primarykey);
            jQuery(tblname).setGridWidth("850", true);
        },
        beforeSelectRow: function (rowid, e) {
            //debugger;
            if (tblname == "#dtgridExist" && $('input:radio[name=radiogrp_imp]:checked').val() == "new") {
                $("#dtgridExist").resetSelection();
                return false;   // not allow select the row
            }
        },
        loadError: function (xhr, status, error) {
            ////////debugger
            alert('error');
        }
    });
    ////debugger
}


function showImportData(str, imp_id, filename) {
    $("#dtImport").GridUnload(); // destroy the grid saving the table and pager
    var result = eval('(' + str + ')');
    var url = "MasterCallback.aspx?operation=get_griddataImport&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&imp_id=" + imp_id;
    fillgridMatch(result, "#dtImport", "#pgImport", "850px", "350px", "Imported Data of " + filename, "", url, false);
}

function refreshMatchGrid(tabname) {
    ////debugger
    if ($("#drp_mstM option:selected").data("TableName") != null && $("#drp_mstM option:selected").data("TableName") != "" && $("#drp_mstM option:selected").data("TableName") != undefined) {
        dimtable_name = $("#drp_mstM option:selected").data("TableName");
    }
    if ($("#drp_mstM").val() != null && $("#drp_mstM").val() != "" && $("#drp_mstM").val() != undefined) {
        list_id = $("#drp_mstM").val();
    }

    rule_id = $("#drp_" + tabname + "rule").val();
    imp_id = $("#hid_ImpId").val();

    var url = null;

    if (tabname == "Match") {
        url = "MasterCallback.aspx?operation=get_griddataMatchRule&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=" + rule_id + "&imp_id=" + imp_id;
    }
    else if (tabname == "UnMatch") {
        url = "MasterCallback.aspx?operation=get_griddataUnMatchRule&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&imp_id=" + imp_id;
    }
    else if (tabname == "Manual") {
        url = "MasterCallback.aspx?operation=get_griddataManualRule&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=" + rule_id + "&imp_id=" + imp_id;
    }

    //refresh the related grid
    refreshgrid("data", "#dtgrid" + tabname, url);

}

// match Apply button click
function MatchApply() {
    //debugger
    var Ids = $("input.cbox:checked", "#dtgridMatch").parent().siblings("[aria-describedby*='_XREF_ID']").text();

    if ($("#dtgridMatch").getGridParam("reccount") > 0 && Ids != "") {

        if ($("#drp_mstM option:selected").data("TableName") != null && $("#drp_mstM option:selected").data("TableName") != "" && $("#drp_mstM option:selected").data("TableName") != undefined) {
            dimtable_name = $("#drp_mstM option:selected").data("TableName");
        }
        if ($("#drp_mstM").val() != null && $("#drp_mstM").val() != "" && $("#drp_mstM").val() != undefined) {
            list_id = $("#drp_mstM").val();
        }

        rule_id = $("#drp_Matchrule").val();
        imp_id = $("#hid_ImpId").val();
        var mastid;

        var jsonstring = "["
        $("input.cbox:checked", "#dtgridMatch").each(function () {
            //////debugger
            var rowid = $(this).parent().parent().attr("id");
            var xrefid = $('#dtgridMatch').getCell(rowid, 'XREF_ID');
            jsonstring = jsonstring + '{"Id" :  "' + xrefid + '"},';

        });

        jsonstring = jsonstring.substring(0, jsonstring.length - 1) + "]";
        ////////////   

        $.ajax({
            async: true,
            type: 'POST',
            // url: "MasterCallback.aspx?operation=matchApply&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=" + rule_id + "&Ids=" + Ids + "&jsonstring=" + jsonstring,
            data: "dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=" + rule_id + "&Ids=" + Ids + "&jsonstring=" + jsonstring + "&imp_id=" + imp_id,
            url: "MasterCallback.aspx?operation=MatchApply",
            success: function (result) {
                //debugger;
                if (result == "false") {
                    alert("Error in match Apply !");
                    return false;
                }
                else if (result == "true") {
                    refreshMatchGrid("Match");
                }
                else if (result == "endproc") {
                    //debugger;
                    endImportProc();
                }
            }
        });
    }
    else {
        alert("There is no record to aplly rule !");
        return false;
    }
}


function endImportProc() {

    //debugger;`
    alert("Existing import process is completed ! ");
    //close all related tab
    $('#tabsDimm').tabs('remove', 5); //un-match tab
    $('#tabsDimm').tabs('remove', 4); //manual tab
    $('#tabsDimm').tabs('remove', 3); //match tab                  

    //refresh existing process grid
    listIdImport = $("#drp_mstM").val();
    var url = "MasterCallback.aspx?operation=fillExistProcGridData&list_id=" + listIdImport;
    refreshgrid("data", "#dtgridExist", url);
    $("#txtUpload").val('');  //txtUpload
    $("#txtExcel").val('');
    //import grid refresh
    $("#dtImport").GridUnload();
    $("#tabsDimmCaption").text('');

    $("#tabsDimm").tabs("select", 1);

}

// match Apply button click
function ManualApply() {

    //////debugger

    var Ids = $("input.cbox:checked", "#dtgridManual").parent().siblings("[aria-describedby*='_XREF_ID']").text();

    if ($("#dtgridManual").getGridParam("reccount") > 0 && Ids != "") {

        //dimtable_name = $("#drp_mstM option:selected").data("TableName");
        //list_id = $("#drp_mstM").val();
        if ($("#drp_mstM option:selected").data("TableName") != null && $("#drp_mstM option:selected").data("TableName") != "" && $("#drp_mstM option:selected").data("TableName") != undefined) {
            dimtable_name = $("#drp_mstM option:selected").data("TableName");
        }
        if ($("#drp_mstM").val() != null && $("#drp_mstM").val() != "" && $("#drp_mstM").val() != undefined) {
            list_id = $("#drp_mstM").val();
        }

        rule_id = $("#drp_Manualrule").val();
        var mastid = null;
        imp_id = $("#hid_ImpId").val();

        var jsonstring = "["
        $("input.cbox:checked", "#dtgridManual").each(function () {
            //////debugger
            var rowid = $(this).parent().parent().attr("id");
            var xrefid = $('#dtgridManual').getCell(rowid, 'XREF_ID');

            //multimast means multiple matching master is there
            //if it is true then check for checkbox checked attr else take 
            //dimid directly
            if ($(this).attr("multimast") == "true") {
                if (mastid == null) {
                    mastid = $('input[type="checkbox"][offval="no"][xrefid="' + xrefid + '"]:checked', "#dtgridManual").attr("dimid");
                }
                else {
                    mastid = mastid + $('input[type="checkbox"][offval="no"][xrefid="' + xrefid + '"]:checked', "#dtgridManual").attr("dimid");
                }
            }

            jsonstring = jsonstring + '{"Id" :  "' + xrefid + '", "mastid" :  "' + mastid + '"},';

        });

        jsonstring = jsonstring.substring(0, jsonstring.length - 1) + "]";

        //alert(jsonstring);
        // ////debugger

        $.ajax({
            async: true,
            type: 'POST',
            data: "dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=" + rule_id + "&jsonstring=" + jsonstring + "&imp_id=" + imp_id,
            url: "MasterCallback.aspx?operation=manualMatchApply",
            success: function (result) {
                //debugger;
                if (result == "false") {
                    alert("Error in manual match Apply !");
                    return false;
                }
                else if (result == "true") {
                    refreshMatchGrid("Manual");
                }
                else if (result == "endproc") {
                    //debugger;
                    endImportProc();
                }
            }
        });
    }
    else {
        alert("There is no record to aplly rule !");
        return false;
    }
}

// un-match Apply button click
function UnMatchApply() {

    var Ids = $("input.cbox:checked", "#dtgridUnMatch").parent().siblings("[aria-describedby*='_XREF_ID']").text();

    if ($("#dtgridUnMatch").getGridParam("reccount") > 0 && Ids != "") {

        //debugger;
        if ($("#drp_mstM option:selected").data("TableName") != null && $("#drp_mstM option:selected").data("TableName") != "" && $("#drp_mstM option:selected").data("TableName") != undefined) {
            dimtable_name = $("#drp_mstM option:selected").data("TableName");
        }
        if ($("#drp_mstM").val() != null && $("#drp_mstM").val() != "" && $("#drp_mstM").val() != undefined) {
            list_id = $("#drp_mstM").val();
        }

        //////debugger
        imp_id = $("#hid_ImpId").val();

        var jsonstring = "["
        $("input.cbox:checked", "#dtgridUnMatch").parent().siblings("[aria-describedby*='_XREF_ID']").each(function () {
            //debugger;
            jsonstring = jsonstring + '{"Id" :  "' + $(this).text() + '"},';
        });

        jsonstring = jsonstring.substring(0, jsonstring.length - 1) + "]";
        ////////////

        $.ajax({
            async: true,
            type: 'POST',
            data: "dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&Ids=" + Ids + "&jsonstring=" + jsonstring + "&imp_id=" + imp_id,
            url: "MasterCallback.aspx?operation=UnmatchApply",
            success: function (result) {
                //////debugger
                if (result == "false") {
                    alert("Error in save to master !");
                    return false;
                }
                else if (result == "true") {
                    refreshMatchGrid("UnMatch");
                }
                else if (result == "endproc") {
                    endImportProc();
                }
            }
        });
    }
    else {
        alert("There is no record to Save to master !");
        return false;
    }
}

function addtab(tabname, dispalyname) {

    var len = $('#tabsDimm').tabs('length');
    var obj = [
        {
            name: tabname
        }];

    $("#tabsDimm").tabs("add", "#tabsDimm-" + len, dispalyname);
    $("#tmplDynMatchRes").tmpl(obj).appendTo("#tabsDimm-" + (len));

    //debugger;
    //css of dimension tab (to make a class and apply)
    $("#tabsDimm-" + (len)).css("align", "center");
    $("#tabsDimm-" + (len)).addClass("tabsDimm");

}

//add manual tab dynamically
function addMatchTab(str, imp_id, bAddtab) {

    //debugger;
    var arr = str.split('^');

    var result = arr[0];
    var tabname = "Match";

    //if addtab=true then do this
    if (bAddtab == true) {
        addtab("Match", "Match");
        $("#tabsDimm").tabs("select", 3);
    }

    var result = eval('(' + arr[0] + ')');
    var colN = result.columns, colM = result.colModelList;

    $("#dtgrid" + tabname).GridUnload(); // destroy the grid saving the table and pager
    colN.splice(1, 1); // Remove 1 item starting from index 1 
    colM.splice(1, 1); // Remove 1 item starting from index 1

    jQuery("#dtgrid" + tabname).jqGrid({
        async: false,
        url: "MasterCallback.aspx?operation=get_griddataMatchRule&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=0" + "&imp_id=" + imp_id,
        datatype: 'json',
        gridview: true,
        colNames: result.columns,
        colModel: result.colModelList,
        caption: "Master Data",
        pager: "#pg" + tabname,
        sortorder: "desc",
        width: "800px",
        height: "100%",
        sortable: false,
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        pgbuttons: false,
        rowNum: -1,
        multiselect: true,
        loadComplete: function (data) {

            //debugger;
            //color golden records
            $(this).find("tr.jqgrow:has(td:[aria-describedby*='_MANUAL_RULE_ID'][title='0.00'])").addClass("golden");

            jQuery("#dtgrid" + tabname).hideCol(result.primarykey);
            jQuery("#dtgrid" + tabname).setGridWidth("850", true);

            if (data.rows.length > 0) {
                for (var i = 0; i < data.rows.length; i++) {
                    var rowid = data.rows[i].cell[0];
                    var val = $(this).jqGrid('getCell', rowid, 'MANUAL_RULE_ID');
                    if (val == '0.00') {
                        $("#jqg_dtgrid" + tabname + "_" + rowid).hide();
                        $("#jqg_dtgrid" + tabname + "_" + rowid).attr('disabled', 'true');
                    }
                }
            }
        },
        onSelectAll: function (aRowids, status) {
            if (status) {
                // uncheck "protected" rows
                var cbs = $("tr.jqgrow > td > input.cbox:disabled", "#dtgrid" + tabname);
                cbs.removeAttr("checked");
                jQuery("#dtgrid" + tabname).find("tr.jqgrow:has(td > input.cbox:disabled)").removeClass("ui-state-highlight");

                //modify the selarrrow parameter
                jQuery(dtgrid).p.selarrrow = jQuery(dtgrid).find("tr.jqgrow:has(td > input.cbox:checked)")
                                .map(function () { return this.id; }) // convert to set of ids
                                .get(); // convert to instance of Array
            }
        },
        loadError: function (xhr, status, error) {
            alert('error');
        }
    });

    jQuery("#dtgrid" + tabname).jqGrid('navGrid', "#pg" + tabname, { edit: false, add: false, del: false, search: true });
    //jQuery("#dtgrid" + tabname).jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false }); 

}

function SendToUnMatch(tabname) {

    ////debugger
    //alert(tabname);
    var dtgridname = "#dtgrid" + tabname;
    imp_id = $("#hid_ImpId").val();


    if ($(dtgridname).getGridParam("reccount") > 0) {

        if (confirm("All data will be sent to un-match. Do you want to Continue ? ")) {

            if ($("#drp_mstM option:selected").data("TableName") != null && $("#drp_mstM option:selected").data("TableName") != "" && $("#drp_mstM option:selected").data("TableName") != undefined) {
                dimtable_name = $("#drp_mstM option:selected").data("TableName");
            }
            if ($("#drp_mstM").val() != null && $("#drp_mstM").val() != "" && $("#drp_mstM").val() != undefined) {
                list_id = $("#drp_mstM").val();
            }
            rule_id = $("#drp_" + tabname + "rule").val();

            $.ajax({
                async: true,
                type: 'POST',
                // url: "MasterCallback.aspx?operation=matchApply&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=" + rule_id + "&Ids=" + Ids + "&jsonstring=" + jsonstring,
                data: "dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&rule_id=" + rule_id + "&imp_id=" + imp_id,
                url: "MasterCallback.aspx?operation=" + tabname + "SendtoUnMatch",
                success: function (result) {
                    //////debugger
                    if (result == "false") {
                        alert("Error in match Apply !");
                        return false;
                    }
                    else {
                        refreshMatchGrid(tabname);
                        //refresh un-match grid
                        refreshMatchGrid("UnMatch");
                    }
                }
            });
        }
    }
    else {
        alert("There is no record to 'Send to Un-match'!");
        return false;
    }
}


function disableControls() {

    //debugger;

    var selection = $('input:radio[name=radiogrp_imp]:checked').val();
    var nonselection = $('input:radio[name=radiogrp_imp]:not(:checked)').val();
    $("#div_" + selection + " :input").removeAttr('disabled');
    $("#div_" + nonselection + " :input").attr('disabled', 'disabled');

    if (selection == "new") {
        // $('#fileupload1', document.forms["formImport"]).attr('disabled', 'disabled');
        //$('#MSubmit_Import').attr('disabled', 'disabled'); //MSubmit_Import
        //$('#MSubmit_matchRule').attr('disabled', 'disabled'); //MSubmit_matchRule

        // $('#div_exist').block({ message: null });
        //$('#div_new').unblock(); 

    }
    else {
        //--refesh grid if listid is changed then
        //fill existing processes in grid        
        //if(listIdImport != $("#drp_mstM").val())
        //{
        //refreshGridExist();
        // $('#div_exist').unblock();
        // $('#div_new').block({ message: null });

        listIdImport = $("#drp_mstM").val();
        var url = "MasterCallback.aspx?operation=fillExistProcGridData&list_id=" + listIdImport;
        refreshgrid("data", "#dtgridExist", url);
        //}
        //$('#MSubmit_Import').removeAttr('disabled');
        //$('#MSubmit_matchRule').removeAttr('disabled');
    }
}

//fill existing processes in grid 
function fillExistProcGrid() {
    ////debugger
    $.ajax({
        async: false,
        type: 'POST',
        url: "MasterCallback.aspx?operation=fillExistProcGrid",
        success: function (result) {
            //debugger;
            if (result == "false") {
                alert("Error in match Apply !");
                return false;
            }
            else {
                fillgridExistImp(result);
            }
        }
    });

    //    disableControls();
    var selection = $('input:radio[name=radiogrp_imp]:checked').val();
    var nonselection = $('input:radio[name=radiogrp_imp]:not(:checked)').val();
    $("#div_" + selection + " :input").removeAttr('disabled');
    $("#div_" + nonselection + " :input").attr('disabled', 'disabled');
}

function fillgridExistImp(str) {
    //debugger;
    var result = eval('(' + str + ')');
    var colD = result.datarow, colN = result.columns, colM = result.colModelList;

    //retain data of import process
    importProcData = colD;
    var url = "MasterCallback.aspx?operation=fillExistProcGridData&list_id=0";
    fillgridMatch(result, "#dtgridExist", "#pgExist", "850x", "350px", "Existing Process", "", url, false);

    //debugger;
    jQuery("#dtgridExist").jqGrid('navGrid', "#pgExist", { view: false, edit: false, add: false, del: false, search: false, refresh: false });

    $("#dtgridExist").jqGrid('navButtonAdd', "#pgExist",
    {
        caption: "",
        title: "Reload Grid",
        buttonicon: "ui-icon-refresh",
        onClickButton: function () {
            //debugger;
            //alert('"Refresh" button is clicked!');
            listIdImport = $("#drp_mstM").val();
            var url = "MasterCallback.aspx?operation=fillExistProcGridData&list_id=" + listIdImport;
            refreshgrid("data", "#dtgridExist", url);
        }
    });

}


function DisplayImpProcess(impId, elm) {

    //debugger;
    //highlight that row
    $("#dtgridExist").jqGrid('setSelection', $(elm).closest('tr').attr('id'));

    var selection = $('input:radio[name=radiogrp_imp]:checked').val();

    if (selection == "exist") {

        list_id = Math.floor($("#dtgridExist").jqGrid('getCell', impId, 'DIM_ID'));
        dimtable_name = $("#dtgridExist").jqGrid('getCell', impId, 'TABLE_NAME');
        var isExecuted = $("#dtgridExist").jqGrid('getCell', impId, 'IS_EXECUTED');
        filename = $("#dtgridExist").jqGrid('getCell', impId, 'EXCEL_FILE_NAME');

        $("#hid_ImpId").val(impId);

        if (isExecuted == "No" || isExecuted == null || isExecuted == "") {
            //show import data
            $.ajax({
                async: false,
                type: 'POST',
                url: "MasterCallback.aspx?operation=get_gridColdataMatchRuleImp&list_id=" + list_id,
                success: function (result) {
                    //debugger;

                    if (result == "false") {
                        alert("Error in showing Import Data !");
                        return false;
                    }
                    else {

                        showImportData(result, impId, filename);
                        //show execute button                      
                        //if ($("#dtImport").getGridParam("reccount")) {
                        $("#MSubmit_matchRule").show();
                        $("#MSubmit_matchRule").removeAttr('disabled');
                        //}
                    }
                }
            });

        }
        else {

            $.ajax({
                async: false,
                type: 'POST',
                url: "MasterCallback.aspx?operation=showExistProc&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&imp_id=" + impId, //isExecuted
                //&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&imp_id=" + imp_id,
                success: function (result) {
                    //debugger;
                    if (result == "false") {
                        alert("Error !");
                        return false;
                    }
                    else {

                        var bflag;
                        //debugger;
                        if ($('#tabsDimm').tabs('length') < 5) {
                            bflag = true;
                        }
                        else {
                            bflag = false;
                        }

                        fillMatchGrid(result, impId, bflag);
                        $("#MSubmit_matchRule").hide();
                    }
                }
            });
        }

        //select match tab
        $("#tabsDimm").tabs("select", 3);

    }

}

function importDimensionChange() {

    ////debugger
    var selection = $('input:radio[name=radiogrp_imp]:checked').val();

    if (selection == "exist") {
        if (listIdImport != $("#drp_mstM").val()) {
            listIdImport = $("#drp_mstM").val();
            var url = "MasterCallback.aspx?operation=fillExistProcGridData&list_id=" + listIdImport;
            refreshgrid("data", "#dtgridExist", url);
        }
    }
    else {

        //refresh  new content
        $("#MSubmit_matchRule").hide();
        if ($("#dtImport").getGridParam("reccount") > 0) {
            $("#txtUpload").val('');  //txtUpload      
        }
        $("#dtImport").GridUnload(); // destroy the grid saving the table and pager

    }
}

function refreshGridExist() {

    //debugger;   

    var colD = importProcData;
    listIdImport = $("#drp_mstM").val();

    var arr = jQuery.grep(importProcData, function (item, i) {
        return (item.DIM_ID == listIdImport)
    });

    var tblname = "#dtgridExist";
    $(tblname).jqGrid("clearGridData", true);

    //refresh jqgrid
    jQuery(tblname).jqGrid('setGridParam',
    {
        data: colD,
        datatype: 'json'
    }).trigger("reloadGrid");

}

function Discard() {

    // debugger
    var tabname = "UnMatch";
    var dtgridname = "#dtgrid" + tabname;


    if ($(dtgridname).getGridParam("reccount") > 0) {
        //dimtable_name = $("#drp_mstM option:selected").data("TableName");
        //list_id = $("#drp_mstM").val();
        if ($("#drp_mstM option:selected").data("TableName") != null && $("#drp_mstM option:selected").data("TableName") != "" && $("#drp_mstM option:selected").data("TableName") != undefined) {
            dimtable_name = $("#drp_mstM option:selected").data("TableName");
        }
        if ($("#drp_mstM").val() != null && $("#drp_mstM").val() != "" && $("#drp_mstM").val() != undefined) {
            list_id = $("#drp_mstM").val();
        }

        imp_id = $("#hid_ImpId").val();

        $.ajax({
            async: true,
            type: 'POST',
            data: "dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&imp_id=" + imp_id,
            url: "MasterCallback.aspx?operation=discard",
            success: function (result) {
                //debugger;
                if (result == "false") {
                    alert("Error in discard data!");
                    return false;
                }
                else if (result == "true") {
                    refreshMatchGrid("UnMatch");
                }
                else if (result == "endproc") {
                    endImportProc();
                }
            }
        });
    }
    else {
        alert("There is no record to 'discard data'!");
        return false;
    }
}


//import relation tab
//import data section for excel
function ImportDataRel() {

    ////debugger
    var Mdimtable_name = $("#drp_mstRel option:selected").data("TableName");
    var Cdimtable_name = $("#drp_chldRel option:selected").data("TableName");

    var Mlist_id = $("#drp_mstRel").val();
    var Clist_id = $("#drp_chldRel").val();

    filepath = $("#frameFileRel").contents().find('#fileuploadRel')[0].value;
    filename = $("#txtUploadRel").val();  //txtUpload
    var sheetname = $("#txtExcelRel").val();  //txtExcel

    if (Mlist_id == Clist_id) {
        alert("Master and Child dimension can't be same !");
        return false;
    }
    else {


        if (sheetname == null || sheetname == "undefined" || sheetname == "") {
            alert("Please Put Excel Sheet Name to Import Data !");
            return false;
        }
        else {

            if (filename == null || filename == "undefined" || filename == "") {
                alert("Please Submit Excel file to Import Data !");
                return false;
            }
            else {
                //debugger
                if (Mlist_id == null || Mlist_id == "undefined" || Mlist_id == "") {
                    alert("Please Select Master dimension to Import Data !");
                    return false;
                }
                else if (Clist_id == null || Clist_id == "undefined" || Clist_id == "") {
                    alert("Please Select Child dimension to Import Data !");
                    return false;
                }
                else {
                    $.ajax({
                        async: true,
                        type: 'POST',
                        // url: "MasterCallback.aspx?operation=ImportDataRel&Mdimtable_name=" + Mdimtable_name + "&Cdimtable_name=" + Cdimtable_name + "&Mlist_id=" + Mlist_id + "&Clist_id=" + Clist_id + "&filename=" + filename + "&sheetname=" + sheetname, //sheetname
                        url: "MasterCallback.aspx?operation=ImportDataRel&Mlist_id=" + Mlist_id + "&Clist_id=" + Clist_id + "&filename=" + filename + "&sheetname=" + sheetname, //sheetname
                        success: function (str) {
                            //debugger;
                            if (str == "false") {
                                alert("Error in Import !");
                                return false;
                            }
                            else if (str == "notmapped") {
                                alert("Columns are not mapped ! Can't be Imported !");
                                return false;
                            }
                            else if (str == "noSheet") {
                                alert("Sheet Name Doesn't exists ! Can't be Imported !");
                                return false;
                            }
                            else {
                                // debugger;
                                //$("#hdn_bAttrVal").attr('value', "1");   
                                var arr = str.split('~');
                                $("#txtUploadRel").val('');  //txtUpload 
                                $("#txtExcelRel").val('');
                                $("#drp_mstRel").val("");
                                $("#drp_chldRel").val("");
                                //drp_mstRel
                                //drp_chldRel
                                alert('Relation data imported successfully !');
                                return false;
                            }
                        }
                    });
                }
            }
        }
    }
}


//show relation data
function loadDimRelData() {

    //debugger;
    ////////
    dimtable_name = $("#drp_mst option:selected").data("TableName");
    list_id = $("#drp_mst").val();
    var mast_id = jQuery("#dataGrid").jqGrid('getGridParam', 'selrow');

    //child list_id --
    var Clist_id = 7;


    if (mast_id == null || mast_id == "undefined") {
        alert("Please Select dimension to show relation data");
        return false;
    }
    else {

        var url = "MasterCallback.aspx?operation=GetRelData&dimtable_name=" + dimtable_name + "&Mlist_id=" + list_id + "&Clist_id=" + Clist_id + "&mast_id=" + mast_id;

        if (Clist_id == Childlist_id) {
            //refresh grid
            //debugger;
            refreshgrid("data", "#datagridRel", url);
            //show and hide div of grid                
            //if ($("#datagridRel").getGridParam("reccount") > 0) {
            //show relation div
            $("#divRel").show();
            //}
            //else {
            //hide relation div
            // $("#divRel").hide();
            //}
        }
        else {

            if (isPopulatedRel == true) { $("#dataGridRel").GridUnload(); } // destroy the grid saving the table and pager
            //if not changed dimension then 
            //debugger;
            $.ajax({

                async: false,
                type: 'GET',
                url: "MasterCallback.aspx?operation=get_gridColdata&list_id=" + Clist_id + "&blink=true",
                data: "",
                dataType: "json",
                success: function (result) {

                    //debugger;
                    var colN = result.columns, colM = result.colModelList;

                    //if first time populating then 
                    if (isPopulatedRel == false) {
                        fillgrid(result, "#datagridRel", "pagerRel", "900px", "100%", url, false);
                        $("#divRel").show();
                        jQuery("#datagridRel").setGridWidth("900", true);
                        isPopulatedRel = true;
                        Childlist_id = Clist_id;
                    }
                    else {
                        //refreshgrid("#datagridRel", "pagerRel", url);
                        refreshgrid("data", "#datagridRel", url);
                    }

                    //                    //show and hide div of grid                
                    //                    if ($("#datagridRel").getGridParam("reccount") > 0) {
                    //                        //show relation div
                    //                        $("#divRel").show();
                    //                    }
                    //                    else {
                    //                        //hide relation div
                    //                        $("#divRel").hide();
                    //                    }

                },
                error: function (x, e) {
                    //////debugger
                    alert(x.readyState + " " + x.status + " " + e.msg);
                }
            });
        }

    }
}


function DisplayDetail(Id, elm) {

    // debugger;
    $("#datagridRel").resetSelection();
    $("#datagridRel").jqGrid('setSelection', $(elm).closest('tr').attr('id'));
    var columnNames = $("#datagridRel").jqGrid('getGridParam', 'colNames');
    var rowData = jQuery("#datagridRel").getRowData(Id);

    var data = JSON.stringify(rowData);
    //alert(String(rowData));
    //alert(data);
    //divDetail
    $("#divDetail").html(data);

}

//------------------------ show graph code -------------------------
function ShowRelData() {

    //debugger;
    //alert("kk");
    $("#M_DimMast").empty();
    $("#MSubmit_Apply").hide();

    dimtable_name = $("#drp_mst option:selected").data("TableName");
    list_id = $("#drp_mst").val();
    var Ids = jQuery("#dataGrid").getGridParam('selarrrow');
    //
    // if ($("#tabsRel").is(':hidden') == true && Ids.length > 0) {
    if (Ids.length > 0 && $("#tabsRel").hasClass("ui-tabs") == false) {

        //        $("#tabsRel").show();
        //tabsRel
        //for tab inside Relation tab
        $(function () {
            $("#tabsRel").tabs({ closable: true });
        });
    }

    //fill relation div
    // ShowRelationDiv();
    if (Ids.length > 0) {
        fillRelatioDiv();
    }

}
